package com.dst.smart.json;

import android.content.Context;
import android.text.TextUtils;

import com.dst.smart.constant.Constants;
import com.dst.smart.model.BasicInfo;

import org.json.JSONObject;

import java.io.File;

public class BasicInfoUtils {
	public static BasicInfo basicInfo = null;
	private static File jsonFile = new File(Constants.REMOTE_PATH
			+ File.separator + "basic_json");

	public static BasicInfo getBasic(Context context) {
		if (basicInfo == null) {
			String json = JSONFileUtils.getJsonStringFromFile(jsonFile)
					.replace("\r\n", "");
			if (TextUtils.isEmpty(json)) {
				basicInfo = new BasicInfo();
				basicInfo.setVol("60");
				basicInfo.setGreetingInfo("主人,您好,我是您的智能管家,叮咚");
				basicInfo.setWakeUpWord("no");
				saveMasterInfo();
			} else {
				try {
					JSONObject object = new JSONObject(json);
					basicInfo = new BasicInfo();
					basicInfo.setVol(object.getString("Vol"));
					basicInfo.setGreetingInfo(object.getString("Greeting"));
					basicInfo.setWakeUpWord(object.getString("WakeUp"));
				} catch (Exception e) {
					// TODO: handle exception
					basicInfo = new BasicInfo();
					basicInfo.setVol("60");
					basicInfo.setGreetingInfo("主人,您好,我是您的智能管家,叮咚");
					basicInfo.setWakeUpWord("no");
					saveMasterInfo();
				}
			}
		}
		return basicInfo ;
	}

	public static void saveMasterInfo() {
		try {
			if (basicInfo != null) {
				JSONObject bject = new JSONObject();
				bject.put("Vol", basicInfo.getVol());
				bject.put("Greeting", basicInfo.getGreetingInfo());
				bject.put("WakeUp", basicInfo.getWakeUpWord());
				JSONFileUtils.saveJSONToFile(jsonFile, bject.toString());
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

}
